package com.linkoog.devtools.utils.formatter;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.linkoog.devtools.utils.StringUtils;

public class JsonFormatter {

   private static ObjectMapper objectMapper = new ObjectMapper();
   static {
       //是否允许解析使用Java/C++ 样式的注释（包括'/'+'*' 和'//' 变量）。
       objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
       //是否允许单引号来包住属性名称和字符串值。
       objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
       //是否将允许使用非双引号属性名字
       objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);

       objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
       objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
       objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
   }

    public static String pretty(String src){
        if (StringUtils.isBlank(src)) return src;

        try {
            JsonNode jsonNode = objectMapper.readTree(src);
            return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
        } catch (Exception e) {
        }
        return src;
    }

    public static String compress(String src){
        if (StringUtils.isBlank(src)) return src;

        try {
            JsonNode jsonNode = objectMapper.readTree(src);
            return objectMapper.writeValueAsString(jsonNode);
        } catch (Exception e) {
        }
        return src;
    }


}
